% based on 'integration' branch: 446a1265c28822456bc0230d362bbabdee7778ba (2012-03-19)

\chapter{IPv4}
\label{cha:ipv4}


\section{Overview}

The IP protocol is the workhorse protocol of the TCP/IP protocol suite.
All UDP, TCP, ICMP packets are encapsulated into IP datagrams and
transported by the IP layer.
While higher layer protocols transfer data among two communication end-point,
the IP layer provides an hop-by-hop, unreliable and connectionless delivery
service. IP does not maintain any state information about the individual
datagrams, each datagram handled independently.

The nodes that are connected to the Internet can be either a host or a router.
The hosts can send and recieve IP datagrams, and their operating system
implements the full TCP/IP stack including the transport layer. On the
other hand, routers have more than one interface cards and perform packet
routing between the connected networks. Routers does not need the
transport layer, they work on the IP level only. The division
between routers and hosts is not strict, because if a host
have several interfaces, they can usually be configured to operate
as a router too.

Each node on the Internet has a unique IP address. IP datagrams contain
the IP address of the destination. The task of the routers is to find
out the IP address of the next hop on the local network, and forward
the packet to it. Sometimes the datagram is larger, than the maximum
datagram that can be sent on the link (e.g. Ethernet has an 1500 bytes limit.).
In this case the datagram is split into fragments and each fragment is
transmitted independently. The destination host must collect all fragments,
and assemble the datagram, before sending up the data to the transport
layer.

\subsection{INET modules}

The INET framework contains several modules to build the
IPv4 network layer of hosts and routers:
\begin{itemize}
  \item \nedtype{IPv4} is the main module that implements RFC791. This
        module performs IP encapsulation/decapsulation, fragmentation
        and assembly, and routing of IP datagrams.
  \item The \nedtype{IPv4RoutingTable} is a helper module that manages the routing
        table of the node. It is queried by the \nedtype{IPv4} module
        for best routes, and updated by the routing daemons implementing
        RIP, OSPF, Manet, etc. protocols.
  \item The \nedtype{ICMP} module can be used to generate ICMP error packets. It also
        supports ICMP echo applications.
  \item The \nedtype{ARP} module performs the dynamic translation of IP addresses
        to MAC addresses.
  \item The \nedtype{IGMPv2} module to generate and process multicast group
        membership reports.
\end{itemize}

These modules are assembled into a complete network layer module
called \nedtype{IPv4NetworkLayer}. This module has
dedicated gates for TCP, UDP, SCTP, RSVP, OSPF, Manet, and Ping
higher layer protocols. It can be connected to several network
interface cards: Ethernet, PPP, Wlan, or external interfaces.
The \nedtype{IPv4NetworkLayer} module is used to build IPv4 hosts
(\nedtype{StandardHost}) and routers (\nedtype{Router}).

The implementation of these modules are based on the following RFCs:
\begin{itemize}
  \item RFC791: Internet Protocol
  \item RFC792: Internet Control Message Protocol
  \item RFC826: Address Resolution Protocol
  \item RFC1122: Requirements for Internet Hosts - Communication Layers
  \item RFC2236: Internet Group Management Protocol, Version 2
\end{itemize}

The subsequent sections describe the IPv4 modules in detail.

\section{The IPv4 Module}

The \nedtype{IPv4} module implements the IPv4 protocol.

For connecting the upper layer protocols the \nedtype{IPv4} module
has \emph{transportIn[]} and \emph{transportOut[]} gate vectors.

The IP packets are sent to the \nedtype{ARP} module through the
\emph{queueOut} gate. The incoming IP packets are received
directly from the network interface cards through the
\emph{queueIn[]} gates. Each interface card knows its own
network layer gate index.

The C++ class of the \nedtype{IPv4} module is derived from \cppclass{QueueBase}.
There is a processing time associated with each incoming packet.
This processing time is specified by the \fpar{procDelay} module parameter.
If a packet arrives, when the processing of a previous has not been
finished, it is placed in a FIFO queue.

The current performance model assumes that each datagram is processed
within the same time, and there is no priority between the datagrams.
If you need a more sophisticated performance model, you may change
the module implementation (the IP class), and:
\begin{enumerate}
  \item override the \ffunc{startService()} method which determines processing
        time for a packet, or
  \item use a different base class.
\end{enumerate}

\subsection{IP packets}

IP datagrams start with a variable length IP header.
The minimum length of the header is 20 bytes, and
it can contain at most 40 bytes for options, so
the maximum length of the IP header is 60 bytes.

\begin{center}
\begin{bytefield}{32}
\bitheader{0,3,4,7,8,15,16,18,19,23,24,31} \\
\bitbox{4}{Version} &
\bitbox{4}{IHL} &
\bitbox{8}{\small Type of Service} &
\bitbox{16}{Total Length} \\
\bitbox{16}{Identification} &
\bitbox{3}{Flags} &
\bitbox{13}{Fragment Offset} \\
\bitbox{8}{Time to Live} &
\bitbox{8}{Protocol} &
\bitbox{16}{Header Checksum} \\
\bitbox{32}{Source Address} \\
\bitbox{32}{Destination Address} \\
\bitbox{24}{Options} &
\bitbox{8}{Padding} \\
\end{bytefield}
\end{center}

The \ttt{Version} field is 4 for IPv4. The 4-bit \ttt{IHL} field is the
number of 32-bit words in the header. It is needed because the header
may contain optional fields, so its length may vary. The minimum IP header
length is 20, the maximum length is 60. The header is always padded to
multiple of 4 bytes. The \ttt{Type of Service} field designed to store
priority and preference values of the IP packet, so applications can
request low delay, high throughput, and maximium reliability from the
routing algorithms. In reality these fields are rarely set by applications,
and the routers mostly ignore them. The \ttt{Total Length} field is the
length of the whole datagram in bytes. The \ttt{Identification} field
is used for identifying the datagram sent by a host. It is usually generated
by incrementing a counter for each outgoing datagram. When the datagram
gets fragmented by a router, its \ttt{Identification} field is kept unchanged
to the other end can collect them. In datagram fragments the \ttt{Fragment Offset}
is the address of the fragment in the payload of the original datagram. It is
measured in 8-byte units, so fragment lengths must be a multiple of 8.
Each fragment except the last one, has its \ttt{MF} (more fragments) bit set
in the \ttt{Flags} field. The other used flag in \ttt{Flags} is the \ttt{DF}
(don't fragment) bit which forbids the fragmentation of the datagram.
The \ttt{Time to Live} field is decremented by each router in the path,
and the datagram is dropped if it reached 0. Its purpose is to prevent
endless cycles if the routing tables are not properly configured, but
can be used for limiting hop count range of the datagram (e.g. for local
broadcasts, but the \fprog{traceroute} program uses this field too).
The \ttt{Protocol} field is for demultiplexing the payload of the IP
datagram to higher level protocols. Each transport protocol has a registered
protocol identifier. The \ttt{Header Checksum} field is the 16-bit one's
complement sum of the header fields considered as a sequence of 16-bit numbers.
The \ttt{Source Address} and \ttt{Destination Address} are the IPv4 addresses
of the source and destination respectively.

The \ttt{Options} field contains 0 or more IP options. It is always padded
with zeros to a 32-bit boundary. An option is either a single-byte option
code or an option code + option length followed by the actual values for
the option. Thus IP implementations can skip unknown options.

An IP datagram is represented by the \msgtype{IPv4Datagram} message class.
It contains variables corresponding the fields of the IP header, except:
\begin{itemize}
  \item \fvar{Header Checksum} omitted, modeled by error bit of packets
  \item \fvar{Options} only the following options are permitted and the
                       datagram can contain at most one option:
        \begin{itemize}
          \item Loose Source Routing
          \item Strict Source Routing
          \item Timestamp
          \item Record Route
        \end{itemize}
\end{itemize}

The \fvar{Type of Service} field is called \ttt{diffServCodePoint} in
\nedtype{IPv4Datagram}.

Before sending the \msgtype{IPv4Datagram} through the network, the \nedtype{IPv4}
module attaches a \cppclass{IPv4RoutingDecision} control info.
The control info contains the IP address of the next hop, and the
identifier of the interface it should be sent. The ARP module translate
the IP address to the hardware address on the local net of the specified
interface and forwards the datagram to the interface card.

\subsection{Interface with higher layer}

Higher layer protocols should be connected to the \ttt{transportIn}/\ttt{transportOut}
gates of the \nedtype{IPv4} module.

\subsubsection*{Sending packets}

Higher layer protocols can send a packet by attaching a \cppclass{IPv4ControlInfo}
object to their packet and sending it to the \nedtype{IPv4} module.

% receiving IP datagrams from higher layer?

The following fields must be set in the control info:
\begin{itemize}
  \item \fvar{procotol}: the \ttt{Protocol} field of the IP datagram. Valid values
        are defined in the \ttt{IPProtocolId} enumeration.
  \item \fvar{destAddr}: the \ttt{Destination Address} of the IP datagram.
\end{itemize}

Optionally the following fields can be set too:
\begin{itemize}
\item \fvar{scrAddr}: \ttt{Source Address} of the IP datagram. If given it must match with the
      address of one of the interfaces of the node, but the datagram is not necessarily
      routed through that interface. If left unspecified, then the address of the
      outgoing interface will be used.
\item \fvar{timeToLive}: TTL of the IP datagram or -1 (unspecified). If unspecified then the TTL
      of the datagram will be 1 for destination addresses in the
      224.0.0.0 -- 224.0.0.255 range. (Datagrams with these special multicast addresses
      do not need to go further that one hop, routers does not forward these datagrams.)
      Otherwise the TTL field is determined by the \fpar{defaultTimeToLive} or
      \fpar{defaultMCTimeToLive} module parameters depending whether the destination
      address is a multicast address or not.
\item \fvar{dontFragment}: the \ttt{Don't Fragment} flag of the outgoing datagram (default is \fkeyword{false})
\item \fvar{diffServCodePoint}: the \ttt{Type of Service} field of the outgoing datagram.
      (ToS is called \ttt{diffServCodePoint} in \msgtype{IPv4Datagram} too.)
\item \fvar{multicastLoop}: if \fkeyword{true}, then a copy of the multicast datagrams
      are sent to the loopback interface, so applications on the same host can receive it.
\item \fvar{interfaceId}: id of outgoing interface (can be used to limit broadcast or restrict routing).
\item \fvar{nextHopAddr}: explicit routing info, used by Manet DSR routing. If specified, then
      \ttt{interfaceId} must also be specified. Ignored in Manet routing is disabled.
\end{itemize}

The IP module encapsulates the transport layer datagram into an \msgtype{IPv4Datagram}
and fills in the header fields according to the control info. The \ttt{Identification}
field is generated by incrementing a counter.

The generated IP datagram is passed to the routing algorithm. The routing decides if the
datagram should be delivered locally, or passed to one of the network interfaces
with a specified next hop address, or broadcasted on one or all of the network interfaces.
The details of the routing is described in the next subsection (\ref{subsec:ip_routing})
in detail.

Before sending the datagram on a specific interface, the \nedtype{IPv4} module
checks if the packet length is smaller than the \ttt{MTU} of the interface.
If not, then the datagram is fragmented. When the \ttt{Don't Fragment} flag
forbids fragmentation, an \ttt{Destination Unreachable} ICMP error is generated
with the \ttt{Fragmentation Error (5)} error code.
\begin{note}
Each fragment will encapsulate the whole higher layer datagram, although the
length of the IP datagram corresponds to the fragment length.
\end{note}

The fragments are sent to the \nedtype{ARP} module through the \ttt{queueOut} gate.
The \nedtype{ARP} module forwards the datagram immediately to point-to-point interface
cards. If the outgoing interface is a 802.x card, then before forwarding the datagram
it performs address resolution to obtain the MAC address of the destination.

\subsubsection*{Receiving packets}

The \nedtype{IPv4} module of hosts processes the datagrams received from the network
in three steps:
\begin{enumerate}
  \item Reassemble fragments
  \item Decapsulate the transport layer datagram
  \item Dispatch the datagram to the appropriate transport protocol
\end{enumerate}

When a fragment received, it is added to the fragment buffer of the IP.
If the fragment was the last fragment of a datagram, the processing of
the datagram continues with step 2. The fragment buffer stores the reception
time of each fragment. Fragments older than \fpar{fragmentTimeout} are
purged from the buffer. The default value of the timeout is 60s. The
timeout is only checked when a fragment is received, and at least 10s
elapsed since the last check.

An \msgtype{IPv4ControlInfo} attached to the decapsulated transport layer packet.
The control info contains fields copied from the IP header (source and destination
address, protocol, TTL, ToS) as well as the interface id through it was received.
The control info also stores the original IP datagram, because the transport
layer might signal an ICMP error, and the ICMP packet must encapsulate the
erronous IP datagram.
\begin{note}
IP datagrams containing a DSR packet are not decapsulated, the unchanged IP
datagram is passed to the DSR module instead.
\end{note}

After decapsulation, the transport layer packet will be passed to the appropriate
transport protocol. It must be connected to one of the \ttt{transportOut[]} gate.
The \nedtype{IPv4} module finds the gate using the \ttt{protocol id}$\rightarrow$
\ttt{gate index} mapping given in the \fpar{protocolMapping} string parameter.
The value must be a comma separated list of ''<protocol\_id>:<gate\_index>'' items.
For example the following line in the ini file maps TCP (6) to gate 0, UDP (17)
to gate 1, ICMP (1) to gate 2, IGMP (2) to gate 3, and RVSP (46) to gate 4.
\begin{inifile}
**.ip.protocolMapping="6:0,17:1,1:2,2:3,46:4"
\end{inifile}
If the protocol of the received IP datagram is not mapped, or the gate
is not connected, the datagram will be silently dropped.
% FIXME (#463) should send DESTINATION_UNREACHABLE/PROTOCOL_UNREACHABLE
% FIXME reassembleAndDeliver() checks that transport gate is connected, but handleReceivedICMP() does not check it

Some protocols are handled differently:
\begin{itemize}
  \item \ttt{ICMP}: ICMP errors are delivered to the protocol
        whose packet triggered the error. Only ICMP query
        requests and responses are sent to the \nedtype{ICMP} module.
  \item \ttt{IP}: sent through \ttt{preRoutingOut} gate. (bug!)
  \item \ttt{DSR}: ??? (subsection about Manet routing?)
\end{itemize}

% FIXME (#462) reassembleAndDeliver(): packets with IP protocol are sent through 'preRoutingOut' gate,
%       but there is no such gate in the IPv4 module.


\subsection{Routing, and interfacing with lower layers}
\label{subsec:ip_routing}

The output of the network interfaces are connected to the
\ttt{queueIn} gates of the \nedtype{IPv4} module. The incoming
packets are either IP datagrams or ARP responses. The IP datagrams
are processed by the \nedtype{IPv4} module, the ARP
responses are forwarded to the \nedtype{ARP}.

The \nedtype{IPv4} module first checks the error bit of the
incoming IP datagrams. There is a $header length/packet length$
probability that the IP header contains the error (assuming
1~bit error). With this probability an ICMP \ttt{Parameter Problem}
generated, and the datagram is dropped.

% FIXME (#466) if IP datagram hasBitError(), but it is decided not be in the IP header,
%       then the decapsulated packet should have the bit error.

When the datagram does not contain error in the IP header,
a routing decision is made. As a result of the routing
the datagram is either delivered locally,
or sent out one or more output interface.
When it is sent out, the routing algorithm must compute the
next hop of its route. The details are differ, depending on
that the destination address is multicast address or not.

When the datagram is decided to be sent up, it is processed
as described in the previous subsection (Receiving packets).
If it is decided to be sent out through some interface, it
is actually sent to the \nedtype{ARP} module through the
\ttt{queueOut} gate. An \msgtype{IPv4RoutingDecision} control
info is attached to the outgoing packet, containing the
outgoing interface id, and the IP address of the next hop.
The \nedtype{ARP} module resolve the IP address to a hardware
address if needed, and forwards the datagram to next hop.

\subsubsection*{Unicast/broadcast routing}

When the higher layer generated the datagram, it will be processed
in these steps:
\begin{enumerate}
  \item If the destination is the address of a local interface,
  then the datagram is locally delivered.
  \item If the destination is the limited broadcast address, or a
  local broadcast address, then it will be broadcasted on one or more
  interface. If the higher layer specified am outgoing interface
  (\fvar{interfaceId} in the control info), then it will be broadcasted
  on that interface only. Otherwise if the \fpar{forceBroadcast} module
  parameter is \fkeyword{true}, then it will broadcasted on all interfaces
  including the loopback interface. The default value of the
  \fpar{forceBroadcast} is \fkeyword{false}.
  \item If the higher layer provided the routing decision (Manet routing),
  then the datagram will be sent through the specified interface to the
  specified next hop.
  \item Otherwise IP finds the outgoing interface and the address of the
  next hop by consulting the routing table, and sends the datagram
  to the next hop. If no route
  found, then a \ttt{Destination Unreachable} ICMP error is generated.
\end{enumerate}


Incoming datagrams having unicast or broadcast destination addresses are
routed in the following steps:

\begin{enumerate}
  \item Deliver datagram locally. If the destination address is a local
  address, the limited broadcast address (255.255.255.255), or a local
  broadcast address, then it will be sent to the transport layer.
  \item Drop packets received from the network when IP forwarding is disabled.
  \item Forward the datagram to the next hop. The next hop is
    determined by looking up the best route to the destination from the
    routing table. If the gateway is set in the route, then the datagram
    will be forwarded to the gateway, otherwise it is sent directly to the
    destination. If no route is found, then
    a \ttt{Destination Unreachable} ICMP error is sent to the source of the
    datagram.
\end{enumerate}

\subsubsection*{Multicast routing}

Outgoing multicast datagrams are handled as follows:
\begin{enumerate}
  \item If the higher layer set the \fvar{multicastLoop} variable
  to \fkeyword{true}, the IP will send up a copy of the datagram
  through the loopback interface.
  \item Determine the outgoing interface for the multicast datagram,
  and send out the datagram through that interface. The outgoing
  interface is determined by the following rules:
  \begin{compactenum}
    \item if the HL specified the outgoing interface in the control
    info, the it will be used
    \item otherwise use the interface of the route configured in the
    routing table for the destination address
    \item if no route found, then use the interface whose address
    matches the source address of the datagram
    \item if the HL did not specify the source address, then use
    the first multicast capable interface
    \item if no such interface found, then the datagram is unroutable
    and droppped
  \end{compactenum}
\end{enumerate}


Incoming multicast datagrams are forwarded according to their source address
(Reverse Path Forwarding), i.e. datagrams are sent away from their sources instead
towards their destinations. The multicast routing table maintains a spanning tree
for each source network and multicast group. The source network is the root of the
tree, and there is a path to each LAN that has members of the multicast group.
Each node expects the multicast datagram to arrive from their parent and forwards
them towards their children. Multicast forwarding loops are avoided by dropping the
datagrams not arrived on the parent interface.

More specifically, the routing routine for multicast datagrams performs these steps:
\begin{enumerate}
  \item Deliver a copy of the datagram locally. If the interface on which
  the datagram arrived belongs to the multicast group specified by the
  destination address, it is sent up to the transport layer.
  \item Discard incoming packets that can not be delivered locally and
  can not be forwarded.
  A non-local packet can not be forwarded if multicast forwarding is disabled,
  the destination is a link local multicast address (224.0.0.x), or
  the TTL field reached 0.
  \item Discard the packet if no multicast route found, or
  if it did not arrive on the parent interface of the route
  (to avoid multicast loops). If the parent is not set in the route,
  then the shortest path interface to the source is assumed.
  \item Forward the multicast datagram.
  A copy of the datagram is sent on each child interface described by
  multicast routes (except the incoming interface). Interfaces may have
  a \fvar{ttlThreshold} parameter, that limits the scope of the multicast:
  only datagrams with higher TTL are forwarded.
\end{enumerate}

\subsection{Parameters}

The \nedtype{IPv4} module has the following parameters:
\begin{itemize}
  \item \fpar{procDelay} processing time of each incoming datagram.
  \item \fpar{timeToLive} default TTL of unicast datagrams.
  \item \fpar{multicastTimeToLive} default TTL of multicast datagrams.
  \item \fpar{protocolMapping} string value containing the \ttt{protocol id}
        $\rightarrow$ \ttt{gate index} mapping, e.g. \ttt{``6:0,17:1,1:2,2:3,46:4''}.
  \item \fpar{fragmentTimeout} the maximum duration until fragments are kept
          in the fragment buffer.
  \item \fpar{forceBroadcast} if \fkeyword{true}, then link-local broadcast
          datagrams are sent out through each interface, if the higher
          layer did not specify the outgoing interface.
\end{itemize}

% compile time options: WITH\_MANET, NEWFRAGMENT

\subsection{Statistics}

The \nedtype{IPv4} module does not write any statistics into files,
but it has some statistical information that can be watched during
the simulation in the gui environment.
\begin{itemize}
  \item \ttt{numForwarded}: number of forwarded datagrams, i.e. sent to one of the
        interfaces (not broadcast), counted before fragmentation.
  \item \ttt{numLocalDeliver}: number of datagrams locally delivered.
        (Each fragment counted separately.)
  \item \ttt{numMulticast}: number of routed multicast datagrams.
  \item \ttt{numDropped} number of dropped packets.
        Either because there is no any interface, the interface is not specified and
        no \fpar{forceBroadcast}, or received from the network but IP forwarding disabled.
  \item \ttt{numUnroutable}: number of unroutable datagrams, i.e. there is no
        route to the destination. (But if outgoing interface is specified it is routed!)
\end{itemize}

In the graphical interface the bubble of the \nedtype{IPv4} module
also displays these counters.


\section{The IPv4RoutingTable module}

The \nedtype{IPv4RoutingTable} module represents the routing table.
IP hosts and routers contain one instance of this class. It has
methods to manage the routing table and the interface table,
so one can achieve functionality similar to the \fprog{route} and
\fprog{ifconfig} commands.

This is a simple module without gates, it requires function calls to it
(message handling does nothing). Methods are provided for reading and
updating the interface table and the route table, as well as for unicast
and multicast routing.

Interfaces are dynamically registered: at the start of the simulation,
every L2 module adds its own interface entry to the table.

The route table is read from a file; the file can
also fill in or overwrite interface settings. The route table can also
be read and modified during simulation, typically by routing protocol
implementations (e.g. OSPF).

Entries in the route table are represented by \cppclass{IPv4Route} objects.
\cppclass{IPv4Route} objects can be polymorphic: if a routing protocol needs
to store additional data, it can simply subclass from \cppclass{IPv4Route},
and add the derived object to the table. The \cppclass{IPv4Route} object
has the following fields:
\begin{itemize}
  \item \ttt{host} is the IP address of the target of the route (can be a host or network).
                   When an entry searched for a given destination address, the destination
                   address is compared with this \ttt{host} address using the \ttt{netmask}
                   below, and the longest match wins.
  \item \ttt{netmask} used when comparing \ttt{host} with the detination address.
                     It is 0.0.0.0 for the default route, 255.255.255.255 for
                     host routes (exact match), or the network or subnet mask
                     for network routes.
  \item \ttt{gateway} is the IP address of the gateway for indirect routes, or
                      0.0.0.0 for direct routes. Note that 0.0.0.0 can be used
                      even if the destination is not directly connected to this
                      node, but can be found using proxy ARP.
  \item \ttt{interface} the outgoing interface to be used with this route.
  \item \ttt{type} \ttt{DIRECT} or \ttt{REMOTE}. For direct routes, the next hop
                   address is the destination address, for remote routes it is
                   the gateway address.
  \item \ttt{source} \ttt{MANUAL}, \ttt{IFACENETMASK}, \ttt{RIP}, \ttt{OSPF},
        \ttt{BGP}, \ttt{ZEBRA}, \ttt{MANET}, or \ttt{MANET2}. \ttt{MANUAL} means
        that the route was added by a routing file, or a network configurator.
        \ttt{IFACENETMASK} routes are added for each interface of the node.
        Other values means that the route is managed by the specific routing
        daemon.
  \item \ttt{metric} the ``cost'' of the route. Currently not used when choosing
                     the best route.
\end{itemize}

% TODO describe Reverse Path Forwarding

In multicast routers the routing table contains multicast routes too.
A multicast route is represented by an instance of the \cppclass{IPv4MulticastRoute}
class. The \cppclass{IPv4MulticastRoute} instance stores the following fields:
\begin{itemize}
  \item \fvar{origin} IP address of the network of the source of the datagram
  \item \fvar{originNetmask} netmask of the source network
  \item \fvar{group} the multicast group to be matched the destination of the
  datagram. If unspecified, then the route matches with
  \item \fvar{parent} interface towards the parent link in the multicast tree.
  Only those datagrams are forwarded that arrived on the parent interface.
  \item \fvar{children} the interfaces on which the multicast datagram to be forwarded.
  Each entry contains a flag indicating if this interface is a leaf in the multicast
  tree. The datagram is forwarded to leaf interfaces only if there are known members
  of the group in the attached LAN.
  \item \fvar{source} enumerated value identifying the creator of the entry. \ttt{MANUAL}
  for static routes, \ttt{DVRMP} for the DVMRP routers, \ttt{PIM\_SM} for PIM SM routers.
  \item \fvar{metric} the ``cost`` of the route.
\end{itemize}

When there are several multicast routes matching the source and destination
of the datagram, then the forwarding algorithm chooses the one with the
\begin{enumerate}
  \item the longest matching source
  \item the more specific group
  \item the smallest metric.
\end{enumerate}

\subsection*{Parameters}

The \nedtype{IPv4RoutingTable} module has the following parameters:

\begin{itemize}
  \item \fpar{routerId}: for routers, the router id using IPv4 address dotted notation;
        specify ``auto'' to select the highest interface address; should be left empty ``''
        for hosts
  \item \fpar{IPForward}: turns IP forwarding on/off (It is always \fkeyword{true}
                          in a \nedtype{Router} and is \fkeyword{false} by default
                          in a \nedtype{StandardHost}.)
  \item \fpar{forwardMulticast}: turns multicast IP forwarding on/off. Default is \fkeyword{false},
  should be set to \fkeyword{true} in multicast routers.
  \item \fpar{routingFile}: name of routing file that configures IP addresses and routes of the node
  containing this routing table. Its format is described in section \ref{subsec:routing_files}.
\end{itemize}

\begin{warning}
The \fpar{routingFile} parameter is obsolete. The prefered method for network configuration
is to use \nedtype{IPv4NetworkConfigurator}. The old config files should be replaced
with the XML configuration of \nedtype{IPv4NetworkConfigurator}. Section \ref{subsec:ipv4configurator}
describes the format of the new configuration files.
\end{warning}

% FIXME (#467) IPv4RoutingTable::invalidateCache() should clear localBroadcastAddresses.
% IPv4RoutingTable::findBestMatchingRoute() should search in this order:
%          1. host routes (exact match)
%          2. network routes (longest match)
%          3. default routes (round robin)
%   It is ok, if host routes has 255.255.255.255 netmask, and default has 0.0.0.0 netmask.
% FIXME IPv4RoutingTable::findBestMatchingRoute() if(...MANET...) branch always set bestRoute to NULL,
%       because if there were exact match, it would have been choosen in the previous loop.

\section{The ICMP module}

The Internet Control Message Protocol (ICMP) is the error reporting and
diagnostic mechanism of the Internet.
It uses the services of IP, so it is a transport layer protocol, but unlike
TCP or UDP it is not used to transfer user data. It can not be separated
from the IP, because the routing errors are reported by ICMP.

The \nedtype{ICMP} module can be used to send error messages and ping
request. It can also respond to incoming ICMP messages.

Each ICMP message is encapsulated within an IP datagram, so its delivery
is unreliable.

\begin{center}
\begin{bytefield}{32}
\bitheader{0,7,8,15,31} \\
\bitbox{8}{Type} &
\bitbox{8}{Code} &
\bitbox{16}{Checksum} \\
\bitbox{32}{Rest of header} \\
\wordbox{2}{Internet Header + 8 bytes of Original Datagram}
\end{bytefield}
\end{center}

The corresponding message class (\msgtype{ICMPMessage}) contains only
the Type and Code fields. The message encapsulates the IP packet that
triggered the error, or the data of the ping request/reply.

% FIXME type=PARAMETER_PROBLEM, code=0: missing Pointer field from ICMPMessage
%            REDIRECT: Gateway Internet Address
%            ECHO_REQUEST, ECHO_REPLY: Identifier, Sequence Number
%            TIMESTAMP_REQUEST, TIMESTAMP_REPLY: Identifier, Sequence Number, Originate Timestamp, Receive Timestamp, Transmit Timestamp

% FIXME wrong type codes for ICMP_DESTINATION_UNREACHABLE (3), ICMP_ECHO_REQUEST (8), ICMP_ECHO_REPLY (0), ICMP_TIMESTAMP_REQUEST (13), ICMP_TIMESTAMP_REPLY (14)

% FIXME ICMP header serializer handles only ICMP_ECHO_REQUEST, ICMP_ECHO_REPLY, ICMP_DESTINATION_UNREACHABLE, ICMP_TIME_EXCEEDED
%       ICMP header deserializer handles only ICMP_ECHO_REQUEST, ICMP_ECHO_REPLY

% FIXME ICMP error should not be send if the original datagram
%         1. is an ICMP error
%         2. was sent to a broadcast or multicast address
%         3. datagram was sent with a link-layer broadcast
%         4. a fragment other than the first
%         5. a datagram whose source address is 0.0.0.0, 127.*.*.*, broadcast or multicast address
%      currently only the 1. and half of 2. checked

The \nedtype{ICMP} module has two methods which can be used by other modules
to send ICMP error messages:
\begin{itemize}
  \item \ffunc[sendErrorMessage]{sendErrorMessage(IPv4Datagram*, ICMPType, ICMPCode)}
        used by the network layer to report erronous IPv4 datagrams. The ICMP header
        fields are set to the given type and code, and the ICMP message will encapsulate
        the given datagram.
  \item \ffunc[sendErrorMessage]{sendErrorMessage(cPacket*, IPv4ControlInfo*, ICMPType, ICMPCode)}
        used by the transport layer components to report erronous packets. The transport
        packet will be encapsulated into an IP datagram before wrapping it into the ICMP message.
\end{itemize}

The \nedtype{ICMP} module can be accessed from other modules of the node by calling
\ffunc{ICMPAccess::get()}.

When an incoming ICMP error message is received, the \nedtype{ICMP} module
sends it out on the \ttt{errorOut} gate unchanged. It is assumed that an
external module is connected to \ttt{errOut} that can process the error
packet. There is a simple module (\nedtype{ErrorHandling}) that simply
logs the error and drops the message. Note that the \nedtype{IPv4} module
does not send REDIRECT, DESTINATION\_UNREACHABLE,
TIME\_EXCEEDED and PARAMETER\_PROBLEM messages to the \nedtype{ICMP} module,
it will send them to the transport layer module that sent the bogus
packet encapsulated in the ICMP message.
\begin{note}
ICMP protocol encapsulates only the IP header + 8 byte following the IP header
from the bogus IP packet. The ICMP packet length computed from this truncated
packet, despite it encapsulates the whole IP message object.
As a consequence, calling \ffunc{decapsulate()} on the ICMP message
will cause an ``packet length became negative'' error. To avoid this,
use \ffunc{getEncapsulatedMsg()} to access the IP packet that caused the ICMP
error.
\end{note}

The \nedtype{ICMP} module receives ping commands on the \ttt{pingIn}
gate from the application. The ping command can be any packet
having an \cppclass{IPv4ControlInfo} control info. The packet
will be encapsulated with an \msgtype{ICMPMessage} and
handed over to the IP.

If \nedtype{ICMP} receives an echo request from IP, the original
message object will be returned as the echo reply. Of course,
before sending back the object to IP, the source and destination
addresses are swapped and the message type changed to ICMP\_ECHO\_REPLY.

When an ICMP echo reply received, the application message decapsulated
from it and passed to the application through the \ttt{pingOut} gate.
The \cppclass{IPv4ControlInfo} also copied from the \msgtype{ICMPMessage}
to the application message.

% FIXME ICMP TIMESTAMP requests are processed as ECHO requests

% \section{The IGMP module}

\section{The ARP module}

The \nedtype{ARP} module implements the Address Resolution Protocol (RFC826).
The ARP protocol is designed to translate a local protocol address
to a hardware address. Altough the ARP protocol can be used with
several network protocol and hardware addressing schemes, in practice
they are almost always IPv4 and 802.3 addresses. The INET implementation
of the ARP protocol (the \nedtype{ARP} module) supports only
IP address $\rightarrow$ MAC address translation.

If a node wants to send an IP packet to a node whose MAC address is unknown,
it broadcasts an ARP frame on the Ethernet network.
In the request its publish its own IP and
MAC addresses, so each node in the local subnet can update their mapping.
The node whose MAC address was requested will respond with an ARP frame
containing its own MAC address directly to the node that sent the
request. When the original node receives the ARP response, it updates
its ARP cache and sends the delayed IP packet using the learned MAC address.

The frame format of the ARP request and reponse is shown in Figure \ref{fig:ARP_frame}.
In our case the HTYPE (hardware type), PTYPE (protocol type), HLEN (hardware address length)
and PLEN (protocol address length) are constants: HTYPE=Ethernet (1), PTYPE=IPv4 (2048), HLEN=6,
PLEN=4. The OPER (operation) field is 1 for an ARP request and 2 for an ARP response.
The SHA field contains the 48-bit hardware address of the sender, SPA field is
the 32-bit IP address of the sender; THA and TPA are the addresses of the target.
The message class corresponding to the ARP frame is \msgtype{ARPPacket}.
In this class only the OPER, SHA, SPA, THA and TPA fields are stored.
The length of an \msgtype{ARPPacket} is 28 bytes.

\begin{figure}[h]
\begin{center}
\label{fig:ARP_frame}
\begin{bytefield}{16}
\bitheader{0,7,8,15} \\
\bitbox{16}{HTYPE} \\
\bitbox{16}{PTYPE} \\
\bitbox{8}{HLEN} &
\bitbox{8}{PLEN} \\
\bitbox{16}{OPER} \\
\wordbox{3}{SHA} \\
\wordbox{2}{SPA} \\
\wordbox{3}{THA} \\
\wordbox{2}{TPA} \\
\end{bytefield}
\caption{ARP frame}
\end{center}
\end{figure}

The \nedtype{ARP} module receives IP datagrams and ARP responses from \nedtype{IPv4}
on the \ttt{ipIn} gate and transmits IP datagrams and ARP requests on the \ttt{nicOut[]} gates
towards the network interface cards. ARP broadcasts the requests on the local network,
so the NIC's entry in the \nedtype{InterfaceTable} should have \ffunc{isBroadcast()} flag
set in order to participate in the address resolution.

The incoming IP packet should have an attached \cppclass{IPv4RoutingDecision} control
info containing the IP address of the next hop. The next hop can be either an
IPv4 broadcast/multicast or a unicast address. The corresponding MAC addresses
can be computed for broadcast and multicast addresses (RFC 1122, 6.4); unicast
addresses are mapped using the ARP procotol.

If the hardware address is found
in the ARP cache, then the packet is transmitted to the addressed interface immediately.
Otherwise the packet is queued and an address resolution takes place.
The \nedtype{ARP} module creates an \msgtype{ARPPacket} object, sets the sender
MAC and IP address to its own address, sets the destination IP address
to the address of the target of the IP datagram, leave the destination MAC address
blank and broadcasts the packet on each network interface with broadcast capability.
Before sending the ARP packet, it retransmission a timer. If the timer expires,
it will retransmit the ARP request, until the maximum retry count is reached.
If there is no response to the ARP request, then the address resolution fails,
and the IP packet is dropped from the queue. Otherwise the MAC address of the
destination is learned and the IP packet can be transmitted on the corresponding
interface.

When an ARP packet is received on the \ttt{ipIn} gate, and the sender's IP
is already in the ARP cache, it is updated with the information in the ARP frame.
Then it is checked that the destination IP of the packet matches with our
address. In this case a new entry is created with the sender addresses in the
ARP cache, and if the packet is a request a response is created and sent directly
to the originator. If proxy ARP is enabled, the request can be responded
with our MAC address if we can route IP packets to the destination.

Usually each \nedtype{ARP} module maintains a local ARP cache.
However it is possible to use a global cache. The global cache is filled
in with entries of the IP and MAC addresses of the known interfaces
when the ARP modules are initiated (at simulation time 0).
\nedtype{ARP} modules that are using the global ARP cache
never initiate an address resolution; if an IP address not
found in the global cache, the simulation stops with an error.
However they will respond to ARP request, so the simulation can
be configured so that some \nedtype{ARP}s use local, while others
the global cache.

When an entry is inserted or updated in the local ARP cache,
the simulation time saved in the entry. The mapping in the
entry is not used after the configured \fpar{cacheTimeout}
elapsed. This parameter does not affect the entries of
the global cache however.

The module parameters of \nedtype{ARP} are:

\begin{itemize}
  \item \fpar{retryTimeout}: number of seconds ARP waits between retries to resolve an IPv4 address (default is 1s)
  \item \fpar{retryCount}: number of times ARP will attempt to resolve an IPv4 address (default is 3)
  \item \fpar{cacheTimeout}: number of seconds unused entries in the cache will time out (default is 120s)
  \item \fpar{proxyARP}: enables proxy ARP mode (default is \fkeyword{true})
  \item \fpar{globalARP}: use global ARP cache (default is \fkeyword{false})
\end{itemize}

The \nedtype{ARP} module emits four signals:

\begin{itemize}
  \item \ttt{sentReq}: emits 1 each time an ARP request is sent
  \item \ttt{sentReplies}: emits 1 each time an ARP response is sent
  \item \ttt{initiatedResolution}: emits 1 each time an ARP resolution is initiated
  \item \ttt{failedResolution}: emits 1 each time an ARP resolution is failed
\end{itemize}

These signals are recorded as vectors and their counts as scalars.

% TODO watches, animation effects

\section{The IGMP module}

The IGMP module is responsible for distributing the information of
multicast group memberships from hosts to routers. When an interface
of a host joins to a multicast group, it will send an IGMP report
on that interface to routers. It can also send reports when the
interface leaves the multicast group, so it does not want to
receive those multicast datagrams. The IGMP module of multicast
routers processes these IGMP reports: it updates the list of
groups, that has members on the link of the incoming message.

The \nedtype{IIGMP} module interface defines the connections
of IGMP modules.
IGMP reports are transmitted by IP, so the module contains
gates to be connected to the IP module (\ttt{ipIn/ipOut}). The IP
module delivers packets with protocol number 2 to the IGMP module.
However some multicast routing protocols (like DVMRP) also exchange
routing information by sending IGMP messages, so they should be
connected to the \ttt{routerIn/routerOut} gates of the IGMP module.
The IGMP module delivers the IGMP messages not processed by itself
to the connected routing module.

The \nedtype{IGMPv2} module implements version 2 of the IGMP protocol
(RFC 2236). Next we describe its behaviour in host and routers in details.
Note that multicast routers behaves as hosts too, i.e. they are sending
reports to other routers when joining or leaving a multicast group.

\subsection{Host behaviour}

When an interface joins to a multicast group, the host
will send a Membership Report immediately to the group address.
This report is repeated after \fpar{unsolicetedReportInterval} to
cover the possibility of the first report being lost.

When a host's interface leaves a multicast group, and it was
the last host that sent a Membership Report for that group,
it will send a Leave Group message to the all-routers multicast
group (224.0.0.2).

This module also responds to IGMP Queries. When the host
receives a Group-Specific Query on an interface that belongs
to that group, then it will set a timer to a random value
between 0 and Max Response Time of the Query. If the timer
expires before the host observe a Membership Report sent
by other hosts, then the host sends an IGMPv2 Membership Report.
When the host receives a General Query on an interface,
a timer is initialized and a report is sent for each group
membership of the interface.

\subsection{Router behaviour}

Multicast routers maintains a list for each interface containing
the multicast groups that have listeners on that interface.
This list is updated when IGMP Membership Reports and Leave Group
messages arrive, or when a timer expires since the last Query.

When multiple routers are connected to the same link, the one with
the smallest IP address will be the Querier. When other routers
observe that they are Non-Queriers (by receiving an IGMP Query
with a lower source address), they stop sending IGMP Queries
until \fpar{otherQuerierPresentInterval} elapsed since the last
received query.

Routers periodically (\fpar{queryInterval}) send a General Query
on each attached network for which this router is a Querier.
On startup the router sends \fpar{startupQueryCount} queries
separated by \fpar{startupQueryInterval}. A General Query
has unspecified Group Address field, a Max Response Time
field set to \fpar{queryResponseInterval}, and is sent to the
all-systems multicast address (224.0.0.1).

When a router receives a Membership Report, it will add the
reported group to the list of multicast group memberships.
At the same time it will set a timer for the membership
to \fpar{groupMembershipInterval}. Repeated reports restart
the timer. If the timer expires, the router assumes
that the group has no local members, and multicast traffic
is no more forwarded to that interface.

When a Querier receives a Leave Group message for a group,
it sends a Group-Specific Query to the group being left.
It repeats the Query \fpar{lastMemberQueryCount} times in
separated by \fpar{lastMemberQueryInterval} until a Membership
Report is received. If no Report received, then the router
assumes that the group has no local members.

% FIXME IGMPv2 not compatible with IGMPv1 hosts and routers

\subsection{Disabling IGMP}

The IPv4 \nedtype{IPv4NetworkLayer} contains an instance of the IGMP
module. IGMP can be turned off by setting the \fpar{enabled}
parameter to false. When disabled, then no IGMP message
is generated, and incoming IGMP messages are ignored.

\subsection{Parameters}

The following parameters has effects in both hosts and routers:

\begin{itemize}
  \item \fpar{enabled} if \fkeyword{false} then the IGMP module is silent. Default is \fkeyword{true}.
\end{itemize}

These parameters are only used in hosts:

\begin{itemize}
  \item \fpar{unsolicitedReportInterval} the time between repetitions of a
   host's initial report of membership in a group. Default is 10s.
\end{itemize}

Router timeouts are configured by these parameters:

\begin{itemize}
  \item \fpar{robustnessVariable} the IGMP is robust to \fpar{robustnessVariable}-1
   packet losses. Default is 2.
  \item \fpar{queryInterval} the interval between General Queries sent by a Querier.
   Default is 125s.
  \item \fpar{queryResponseInterval} the Max Response Time inserted into General Queries
  \item \fpar{groupMembershipInterval} the amount of time that must pass before
   a multicast router decides there are no more members of a group on a network.
   Fixed to \fpar{robustnessVariable} * \fpar{queryInterval} + \fpar{queryResponseInterval}.
  \item \fpar{otherQuerierPresentInterval} the length of time that must
   pass before a multicast router decides that there is no longer
   another multicast router which should be the querier.
   Fixed to \fpar{robustnessVariable} * \fpar{queryInterval} + \fpar{queryResponseInterval} / 2.
  \item \fpar{startupQueryInterval} the interval between General Queries
   sent by a Querier on startup. Default is \fpar{queryInterval} / 4.
  \item \fpar{startupQueryCount} the number of Queries sent out on startup,
   separated by the \fpar{startupQueryInterval}. Default is \fpar{robustnessVariable}.
  \item \fpar{lastMemberQueryInterval} the Max Response Time inserted into
   Group-Specific Queries sent in response to Leave Group messages, and
   is also the amount of time between Group-Specific Query messages.
   Default is 1s.
  \item \fpar{lastMemberQueryCount} the number of Group-Specific Queries
   sent before the router assumes there are no local members.
   Default is \fpar{robustnessVariable}.
\end{itemize}

\section{The IPv4NetworkLayer module}

The \nedtype{IPv4NetworkLayer} module packs the \nedtype{IP}, \nedtype{ICMP},
\nedtype{ARP}, and \nedtype{IGMP} modules into one compound module.
The compound module defines gates for connecting UDP, TCP, SCTP, RSVP and
OSPF transport protocols. The \ttt{pingIn} and \ttt{pingOut} gates of the
\nedtype{ICMP} module are also available, while its \ttt{errorOut} gate
is connected to an inner \nedtype{ErrorHandling} component that writes
the ICMP errors to the log.

The component can be used in hosts and routers to support IPv4.

\section{The NetworkInfo module}

The \nedtype{NetworkInfo} module can be used to dump detailed information
about the network layer. This module does not send or received messages,
it is invoked by the \nedtype{ScenarioManager} instead. For example
the following \nedtype{ScenarioManager} script dump the routing table
of the \ttt{LSR2} module at simulation time $t=2$ into \ffilename{LSR2\_002.txt}:
\begin{filelisting}
<scenario>
  <at t="2">
    <routing module="NetworkInfo" target="LSR2" file="LSR2_002.txt"/>
  </at>
</scenario>
\end{filelisting}

The module currently support only the \ttt{routing} command which dumps
the routing table. The command has four parameters given as XML attributes:
\begin{itemize}
  \item \ttt{target} the name of the node that owns the routing table to be dumped
  \item \ttt{filename} the name of the file the output is directed to
  \item \ttt{mode} if set to ``a'', the output is appended to the file,
                   otherwise the target is truncated if the file existed
  \item \ttt{compat} if set to ``linux'', then the output is generated
                     in the format of the \ttt{route -n} command of Linux.
                     The output is sorted only if \ttt{compat} is
                     \fkeyword{true}.
\end{itemize}

\section{Configuring IPv4 networks}

An IPv4 network is composed of several nodes like hosts, routers,
switches, hubs, Ethernet buses, or wireless access points.
The nodes having a IPv4 network layer (hosts and routers) should be
configured at the beginning of the simulation. The configuration
assigns IP addresses to the nodes, and fills their routing tables.
If multicast forwarding is simulated, then the multicast routing
tables also must be filled in.

% TODO define nodes, IP nodes, routers, multicast routers

The configuration can be manual (each address and route is fully specified
by the user), or automatic (addresses and routes are generated by
a configurator module at startup).

Before version 1.99.4 INET offered \nedtype{FlatNetworkConfigurator}
for automatic and routing files for manual configuration.
Both had serious limitations, so a new configurator has been added
in version 1.99.4: \nedtype{IPv4NetworkConfigurator}. This configurator
supports both fully manual and fully automatic configuration. It
can also be used with partially specified manual configurations,
the configurator fills in the gaps automatically.

The next section describes the usage of \nedtype{IPv4NetworkConfigurator},
\nedtype{FlatNetworkConfigurator} and old routing files are described
in the following sections.

\subsection{IPv4NetworkConfigurator}
\label{subsec:ipv4configurator}

The \nedtype{IPv4NetworkConfigurator} assigns IP addresses and sets up
static routing for an IPv4 network.

It assigns per-interface IP addresses, strives to take subnets into account,
and can also optimize the generated routing tables by merging routing entries.

Hierarchical routing can be set up by using only a fraction of configuration
entries compared to the number of nodes. The configurator also does
routing table optimization that significantly decreases the size of routing
tables in large networks.

The configuration is performed in stage 2 of the initialization. At this
point interface modules (e.g. PPP) has already registered their interface
in the interface table. If an interface is named \ttt{ppp[0]}, then the
corresponding interface entry is named \ttt{ppp0}. This name can be used
in the config file to refer to the interface.

The configurator goes through the following steps:
\begin{enumerate}
  \item  Builds a graph representing the network topology. The graph
     will have a vertex for every module that has a @node property (this
     includes hosts, routers, and L2 devices like switches, access points,
     Ethernet hubs, etc.) It also assigns weights to vertices and edges that
     will be used by the shortest path algorithm when setting up routes.
     Weights will be infinite for IP nodes that have IP forwarding disabled
     (to prevent routes from transiting them), and zero for all other nodes
     (routers and and L2 devices). Edge weights are chosen to be inversely
     proportional to the bitrate of the link, so that the configurator
     prefers connections with higher bandwidth. For internal purposes,
     the configurator also builds a table of all "links" (the link data
     structure consists of the set of network interfaces that are
     on the same point-to-point link or LAN)

  \item  Assigns IP addresses to all interfaces of all nodes. The
     assignment process takes into consideration the addresses and netmasks
     already present on the interfaces (possibly set in earlier initialize
     stages), and the configuration provided in the XML format (described
     below). The configuration can specify "templates" for the address
     and netmask, with parts that are fixed and parts that can be chosen
     by the configurator (e.g. "10.0.x.x"). In the most general case,
     the configurator is allowed to choose any address and netmask for all
     interfaces (which results in automatic address assignment). In the most
     constrained case, the configurator is forced to use the requested addresses
     and netmasks for all interfaces (which translates to manual address assignment).
     There are many possible configuration options between these two extremums. The
     configurator assigns addresses in a way that maximizes the number of
     nodes per subnet. Once it figures out the nodes that belong to a single
     subnet it, will optimize for allocating the longest possible netmask.
     The configurator might fail to assign netmasks and addresses according
     to the given configuration parameters; if that happens, the assignment
     process stops and an error is signalled.

  \item  Adds the manual routes that are specified in the configuration.

  \item  Adds static routes to all routing tables in the network. The
     configurator uses Dijkstra's weighted shortest path algorithm to find
     the desired routes between all possible node pairs. The resulting
     routing tables will have one entry for all destination interfaces in the
     network. The configurator can be safely instructed to add default routes
     where applicable, significantly reducing the size of the host routing
     tables. It can also add subnet routes instead of interface routes further
     reducing the size of routing tables. Turning on this option requires
     careful design to avoid having IP addresses from the same subnet on
     different links. CAVEAT: Using manual routes and static route generation
     together may have unwanted side effects, because route generation ignores
     manual routes.

  \item  Then it optimizes the routing tables for size. This optimization allows
     configuring larger networks with smaller memory footprint and makes the
     routing table lookup faster. The resulting routing table might be
     different in that it will route packets that the original routing table
     did not. Nevertheless the following invariant holds: any packet routed
     by the original routing table (has matching route) will still be routed
     the same way by the optimized routing table.

  \item  Finally it dumps the requested results of the configuration. It can
     dump network topology, assigned IP addresses, routing tables and its
     own configuration format.
\end{enumerate}

The module can dump the result of the configuration in the XML format
which it can read. This is useful to save the result of a time consuming
configuration (large network with optimized routes), and use it as
the config file of subsequent runs.

\subsubsection*{Network topology graph}

The network topology graph is constructed from the nodes
of the network. The node is a module having a @node property
(this includes hosts, routers, and L2 devices like switches,
 access points, Ethernet hubs, etc.). An IP node is a node
that contains an \nedtype{InterfaceTable} and a \nedtype{IPv4RoutingTable}.
A router is an IP node that has multiple network interfaces,
and IP forwarding is enabled in its routing table module.
In multicast routers the \fpar{forwardMulticast} parameter
is also set to \fkeyword{true}.

A link is a set of interfaces that can send datagrams to each other
without intervening routers. Each interface belongs to exactly
one link. For example two interface connected
by a point-to-point connection forms a link. Ethernet interfaces
connected via buses, hubs or switches.
The configurator identifies links by discovering
the connections between the IP nodes, buses, hubs, and switches.

Wireless links are identified by the \fpar{ssid} or \fpar{accessPointAddress}
parameter of the 802.11 management module. Wireless interfaces
whose node does not contain a management module are supposed
to be on the same wireless link. Wireless links can also be
configured in the configuration file of \nedtype{IPv4NetworkConfigurator}:
\begin{verbatim}
<config>
  <wireless hosts="area1.*" interfaces="wlan*">
</config>
\end{verbatim}
puts wlan interfaces of the specified hosts into the same wireless link.

If a link contains only one router, it is marked as the gateway
of the link. Each datagram whose destination is outside the link
must go through the gateway.

\subsubsection*{Address assignment}

Addresses can be set up manually by giving the address and netmask for
each IP node. If some part of the address or netmask is unspecified,
then the configurator can fill them automatically. Unspecified fields
are given as an ``x'' character in the dotted notation of the address.
For example, if the address is specified as 192.168.1.1 and the
netmask is 255.255.255.0, then the node address will be 192.168.1.1
and its subnet is 192.168.1.0. If it is given as 192.168.x.x and
255.255.x.x, then the configurator chooses a subnet address in the range
of 192.168.0.0 - 192.168.255.252, and an IP address within the chosen
subnet. (The maximum subnet mask is 255.255.255.252 allows 2 nodes in the subnet.)

The following configuration generates network addresses below the 10.0.0.0
address for each link, and assign unique IP addresses to each host:

\begin{verbatim}
<config>
  <interface hosts="*" address="10.x.x.x" netmask="255.x.x.x"/>
</config>
\end{verbatim}

The configurator tries to put nodes on the same link into the same subnet,
so its enough to configure the address of only one node on each link.

The following example configures a hierarchical network in a way that keeps
routing tables small.
\begin{verbatim}
<config>
  <interface hosts="area11.lan1.*" address="10.11.1.x" netmask="255.255.255.x"/>
  <interface hosts="area11.lan2.*" address="10.11.2.x" netmask="255.255.255.x"/>
  <interface hosts="area12.lan1.*" address="10.12.1.x" netmask="255.255.255.x"/>
  <interface hosts="area12.lan2.*" address="10.12.2.x" netmask="255.255.255.x"/>
  <interface hosts="area*.router*" address="10.x.x.x" netmask="x.x.x.x"/>
  <interface hosts="*" address="10.x.x.x" netmask="255.x.x.0"/>
</config>
\end{verbatim}

The XML configuration must contain exactly one \verb!<config>! element. Under the
root element there can be multiple of the following elements:

The interface element provides configuration parameters for one or more
interfaces in the network. The selector attributes limit the scope where
the interface element has effects. The parameter attributes limit the
range of assignable addresses and netmasks.
The \verb!<interface>! element may contain the following attributes:
\begin{compactitem}
    \item \ttt{@hosts}
      Optional selector attribute that specifies a list of host name patterns.
      Only interfaces in the specified hosts are affected. The pattern might
      be a full path starting from the network, or a module name anywhere in
      the hierarchy, and other patterns similar to ini file keys. The default
      value is "*" that matches all hosts.
      e.g. "subnet.client*" or "host* router[0..3]" or "area*.*.host[0]"

    \item \ttt{@names}
      Optional selector attribute that specifies a list of interface name
      patterns. Only interfaces with the specified names are affected. The
      default value is "*" that matches all interfaces.
      e.g. "eth* ppp0" or "*"

    \item \ttt{@towards}
      Optional selector attribute that specifies a list of host name patterns.
      Only interfaces connected towards the specified hosts are affected. The
      specified name will be matched against the names of hosts that are on
      the same LAN with the one that is being configured. This works even if
      there's a switch between the configured host and the one specified here.
      For wired networks it might be easier to specify this parameter instead
      of specifying the interface names. The default value is "*".
      e.g. "ap" or "server" or "client*"

    \item \ttt{@among}
      Optional selector attribute that specifies a list of host name patterns.
      Only interfaces in the specified hosts connected towards the specified
      hosts are affected.
      The 'among="X Y Z"' is same as 'hosts="X Y Z" towards="X Y Z"'.

    \item \ttt{@address}
      Optional parameter attribute that limits the range of assignable
      addresses. Wildcards are allowed with using 'x' as part of the address
      in place of a byte. Unspecified parts will be filled automatically by
      the configurator. The default value "" means that the address will not
      be configured. Unconfigured interfaces still have allocated addresses
      in their subnets allowing them to become configured later very easily.
      e.g. "192.168.1.1" or "10.0.x.x"

    \item \ttt{@netmask}
      Optional parameter attribute that limits the range of assignable
      netmasks. Wildcards are allowed with using 'x' as part of the netmask
      in place of a byte. Unspecified parts will be filled automatically be
      the configurator. The default value "" means that any netmask can be
      configured.
      e.g. "255.255.255.0" or "255.255.x.x" or "255.255.x.0"

    \item \ttt{@mtu}                number
      Optional parameter attribute to set the MTU parameter in the interface.
      When unspecified the interface parameter is left unchanged.

    \item \ttt{@metric}                number
      Optional parameter attribute to set the Metric parameter in the interface.
      When unspecified the interface parameter is left unchanged.
\end{compactitem}

Wireless interfaces can similarly be configured by adding
\verb!<wireless>! elements to the configuration. Each \verb!<wireless>!
element with a different id defines a separate subnet.
\begin{compactitem}
    \item \ttt{@id} (optional)
      identifies wireless network, unique value used if missed

    \item \ttt{@hosts}
      Optional selector attribute that specifies a list of host name patterns.
      Only interfaces in the specified hosts are affected. The default value
      is "*" that matches all hosts.

    \item \ttt{@interfaces}
      Optional selector attribute that specifies a list of interface name
      patterns. Only interfaces with the specified names are affected. The
      default value is "*" that matches all interfaces.
\end{compactitem}


\subsubsection{Multicast groups}

Multicast groups can be configured by adding \verb!<multicast-group>!
elements to the configuration file. Interfaces belongs to a multicast
group will join to the group automatically.

For example
\begin{verbatim}
<config>
  <multicast-group hosts="router*" interfaces="eth*" address="224.0.0.5"/>
</config>
\end{verbatim}
adds all Ethernet interfaces of nodes whose name starts with ``router''
to the 224.0.0.5 multicast group.

The \verb!<multicast-group>! element has the following attributes:
\begin{compactitem}
    \item \ttt{@hosts}
      Optional selector attribute that specifies a list of host name patterns.
      Only interfaces in the specified hosts are affected. The default value
      is "*" that matches all hosts.

    \item \ttt{@interfaces}
      Optional selector attribute that specifies a list of interface name
      patterns. Only interfaces with the specified names are affected. The
      default value is "*" that matches all interfaces.

    \item \ttt{@towards}
      Optional selector attribute that specifies a list of host name patterns.
      Only interfaces connected towards the specified hosts are affected.
      The default value is "*".

    \item \ttt{@among}
      Optional selector attribute that specifies a list of host name patterns.
      Only interfaces in the specified hosts connected towards the specified
      hosts are affected.
      The 'among="X Y Z"' is same as 'hosts="X Y Z" towards="X Y Z"'.

    \item \ttt{@address}
      Mandatory parameter attribute that specifies a list of multicast group
      addresses to be assigned. Values must be selected from the valid range
      of multicast addresses.
      e.g. "224.0.0.1 224.0.1.33"
\end{compactitem}


\subsubsection*{Manual route configuration}

The \nedtype{IPv4NetworkConfigurator} module allows the user
to fully specify the routing tables of IP nodes at the beginning
of the simulation.

The \verb!<route>! elements of the configuration add a route to the
routing tables of selected nodes. The element has the following attributes:
\begin{compactitem}
    \item \ttt{@hosts}
      Optional selector attribute that specifies a list of host name patterns.
      Only routing tables in the specified hosts are affected. The default
      value "" means all hosts will be affected.
      e.g. "host* router[0..3]"

    \item \ttt{@destination}
      Optional parameter attribute that specifies the destination address in
      the route (L3AddressResolver syntax). The default value is "*".
      e.g. "192.168.1.1" or "subnet.client[3]" or "subnet.server(ipv4)" or "*"

    \item \ttt{@netmask}
      Optional parameter attribute that specifies the netmask in the route.
      The default value is "*".
      e.g. "255.255.255.0" or "/29" or "*"

    \item \ttt{@gateway}
      Optional parameter attribute that specifies the gateway (next-hop)
      address in the route (L3AddressResolver syntax). When unspecified
      the interface parameter must be specified. The default value is "*".
      e.g. "192.168.1.254" or "subnet.router" or "*"

    \item \ttt{@interface}
      Optional parameter attribute that specifies the output interface name
      in the route. When unspecified the gateway parameter must be specified.
      This parameter has no default value.
      e.g. "eth0"

    \item \ttt{@metric}
      Optional parameter attribute that specifies the metric in the route.
      The default value is 0.
\end{compactitem}

Multicast routing tables can similarly be configured by adding
\verb!<multicast-route>! elements to the configuration.
\begin{compactitem}
    \item \ttt{@hosts}
      Optional selector attribute that specifies a list of host name patterns.
      Only routing tables in the specified hosts are affected.
      e.g. "host* router[0..3]"

    \item \ttt{@source}
      Optional parameter attribute that specifies the address of the source
      network. The default value is "*" that matches all sources.

    \item \ttt{@netmask}
      Optional parameter attribute that specifies the netmask of the source
      network. The default value is "*" that matches all sources.

    \item \ttt{@groups}
      Optional List of IPv4 multicast addresses specifying the groups this entry
      applies to. The default value is "*" that matches all multicast groups.
      e.g. "225.0.0.1 225.0.1.2".

    \item \ttt{@metric}
      Optional parameter attribute that specifies the metric in the route.

    \item \ttt{@parent}
      Optional parameter attribute that specifies the name of the interface
      the multicast datagrams are expected to arrive. When a datagram arrives
      on the parent interface, it will be forwarded towards the child interfaces;
      otherwise it will be dropped. The default value is the interface on the
      shortest path towards the source of the datagram.

    \item \ttt{@children}
      Mandatory parameter attribute that specifies a list of interface name
      patterns:
      \begin{compactitem}
        \item a name pattern (e.g. "ppp*") matches the name of the interface
        \item a 'towards' pattern (starting with ">", e.g. ">router*") matches the interface
         by naming one of the neighbour nodes on its link.
      \end{compactitem}
      Incoming multicast datagrams are forwarded to each child interface except the
      one they arrived in.
\end{compactitem}

The following example adds an entry to the multicast routing table of \ttt{router1},
that intsructs the routing algorithm to forward multicast datagrams whose source
is in the 10.0.1.0 network and whose destinatation address is 225.0.0.1 to
send on the \ttt{eth1} and \ttt{eth2} interfaces assuming it arrived on the
\ttt{eth0} interface:

\begin{verbatim}
<multicast-route hosts="router1" source="10.0.1.0" netmask="255.255.255.0"
                 groups="225.0.0.1" metric="10"
                 parent="eth0" children="eth1 eth2"/>
\end{verbatim}

\subsubsection*{Automatic route configuration}

If the \fpar{addStaticRoutes} parameter is true, then
the configurator add static routes to all routing tables.

The configurator uses Dijkstra's weighted shortest path algorithm to find
the desired routes between all possible node pairs. The resulting
routing tables will have one entry for all destination interfaces in the
network.

%     Weights will be infinite for IP nodes that have IP forwarding disabled
%     (to prevent routes from transiting them), and zero for all other nodes
%     (routers and and L2 devices). Edge weights are chosen to be inversely
%     proportional to the bitrate of the link, so that the configurator
%     prefers connections with higher bandwidth. For internal purposes,

The configurator can be safely instructed to add default routes
where applicable, significantly reducing the size of the host routing
tables. It can also add subnet routes instead of interface routes further
reducing the size of routing tables. Turning on this option requires
careful design to avoid having IP addresses from the same subnet on
different links.


\begin{caution}
Using manual routes and static route generation
together may have unwanted side effects, because route generation ignores
manual routes. Therefore if the configuration file contains
manual routes, then the \fpar{addStaticRoutes} parameter should be set
to \fkeyword{false}.
\end{caution}

\subsubsection*{Route optimization}

If the \fpar{optimizeRoutes} parameter is \fkeyword{true} then the
configurator tries to optimize the routing table for size.
This optimization allows configuring larger networks with smaller
memory footprint and makes the routing table lookup faster.

The optimization is performed by merging routes whose gateway and
outgoing interface is the same by finding a common prefix that
matches only those routes. The resulting routing table might be
different in that it will route packets that the original routing table
did not. Nevertheless the following invariant holds: any packet routed
by the original routing table (has matching route) will still be routed
the same way by the optimized routing table.

\subsubsection*{Parameters}

This list summarize the parameters of the \nedtype{IPv4NetorkConfigurator}:

\begin{params}
  \param{config}
   {XML configuration parameters for IP address assignment and adding manual routes.}
  \param{assignAddresses}
   {assign IP addresses to all interfaces in the network}
  \param{assignDisjunctSubnetAddresses}
   {avoid using the same address prefix and
    netmask on different links when assigning IP addresses to interfaces}
  \param{addStaticRoutes}
   {add static routes to the routing tables of all nodes
    to route to all destination interfaces (only where applicable; turn off when
    config file contains manual routes)}
  \param{addDefaultRoutes}
    {add default routes if all routes from a source node go
     through the same gateway (used only if addStaticRoutes is true)}
  \param{addSubnetRoutes}
   {add subnet routes instead of destination interface routes
    (only where applicable; used only if addStaticRoutes is true)}
  \param{optimizeRoutes}
   {optimize routing tables by merging routes, the resulting routing table might
    route more packets than the original (used only if addStaticRoutes is true)}
  \param{dumpTopology}
   {if true, then the module prints extracted network topology}
  \param{dumpAddresses}
   {if true, then the module prints assigned IP addresses for all interfaces}
  \param{dumpRoutes}
   {if true, then the module prints configured and optimized routing tables for all nodes to
    the module output}
  \param{dumpConfig}
   {name of the file, write configuration into the given config file that can be fed back
    to speed up subsequent runs (network configurations)}
\end{params}

\subsection{FlatNetworkConfigurator}

The \nedtype{FlatNetworkConfigurator} module configures
IP addresses and routes of IP nodes of a network.
All assigned addresses share a common subnet prefix,
the network topology will be ignored. Shortest path
routes are also generated from any node to any other
node of the network. The Gateway (next hop) field of the routes
is not filled in by these configurator, so it relies
on proxy ARP if the network spans several LANs.

% no optimization of routing tables

The \nedtype{FlatNetworkConfigurator} module configures
the network when it is initialized. The configuration
is performed in stage 2, after interface tables are
filled in. Do not use a \nedtype{FlatNetworkConfigurator}
module together with static routing files, because they
can iterfere with the configurator.

The \nedtype{FlatNetworkConfigurator} searches each IP nodes of the network.
(IP nodes are those modules that have the @node NED property and
has a \nedtype{IPv4RoutingTable} submodule named ``routingTable'').
The configurator then assigns IP addresses to the IP nodes, controlled
by the following module parameters:
\begin{itemize}
  \item \fpar{netmask} common netmask of the addresses (default is 255.255.0.0)
  \item \fpar{networkAddress} higher bits are the network part of the addresses,
        lower bits should be 0. (default is 192.168.0.0)
\end{itemize}

With the default parameters the assigned addresses are in the range
192.168.0.1 - 192.168.255.254, so there can be maximum 65534 nodes in the
network. The same IP address will be assigned to each interface
of the node, except the loopback interface which always has address 127.0.0.1
(with 255.0.0.0 mask).

After assigning the IP addresses, the configurator fills in the routing tables.
There are two kind of routes:
\begin{itemize}
  \item default routes: for nodes that has only one non-loopback interface
        a route is added that matches with any destination address
        (the entry has 0.0.0.0 \ttt{host} and \ttt{netmask} fields).
        These are remote routes, but the gateway address is left unspecified.
        The delivery of the datagrams rely on the proxy ARP feature of the
        routers.
  \item direct routes following the shortest paths: for nodes that has more
        than one non-loopback interface a separate route is added to each
        IP node of the network. The outgoing interface is chosen by the
        shortest path to the target node. These routes are
        added as direct routes, even if there is no direct link with the
        destination. In this case proxy ARP is needed to deliver the datagrams.
\end{itemize}

\begin{note}
This configurator does not try to optimize the routing tables.
If the network contains $n$ nodes, the size of all routing tables
will be proportional to $n^2$, and the time of the lookup of the
best matching route will be proportional to $n$.
\end{note}

% FIXME weird FlatNetworkConfigurator behaviour.
%       Assigned IP addresses does not mirror the hierachy of networks (e.g. each node in an Ethernet LAN handled as a one-element subnet).
%       No gateway address is set in the routes, delivery relies on proxy ARPing.
%       Direct routes created to each node, even if there is no direct link to it.
%       Different interfaces of a node should have different IP address.
%       Broadcast capable interfaces should have a real netmast (not 255.255.255.255) to support subnet directed IP broadcasts.

\subsection{Old routing files}
\label{subsec:routing_files}

Routing files are files with \ttt{.irt} or \ttt{.mrt} extension,
and their names are passed in the \fpar{routingFile} parameter
to \nedtype{IPv4RoutingTable} modules.

Routing files may contain network interface configuration and static
routes. Both are optional. Network interface entries in the file
configure existing interfaces; static routes are added to the route table.

Interfaces themselves are represented in the simulation by modules
(such as the PPP module). Modules automatically register themselves
with appropriate defaults in the IPv4RoutingTable, and entries in the
routing file refine (overwrite) these settings.
Interfaces are identified by names (e.g. ppp0, ppp1, eth0) which
are normally derived from the module's name: a module called
\ttt{"ppp[2]"} in the NED file registers itself as interface ppp2.

An example routing file (copied here from one of the example simulations):

\begin{verbatim}
ifconfig:

# ethernet card 0 to router
name: eth0   inet_addr: 172.0.0.3   MTU: 1500   Metric: 1  BROADCAST MULTICAST
Groups: 225.0.0.1:225.0.1.2:225.0.2.1

# Point to Point link 1 to Host 1
name: ppp0   inet_addr: 172.0.0.4   MTU: 576   Metric: 1

ifconfigend.

route:
172.0.0.2   *           255.255.255.255  H  0   ppp0
172.0.0.4   *           255.255.255.255  H  0   ppp0
default:    10.0.0.13   0.0.0.0          G  0   eth0

225.0.0.1   *           255.255.255.255  H  0   ppp0
225.0.1.2   *           255.255.255.255  H  0   ppp0
225.0.2.1   *           255.255.255.255  H  0   ppp0

225.0.0.0   10.0.0.13   255.0.0.0        G  0   eth0

routeend.
\end{verbatim}

The \ttt{ifconfig...ifconfigend.} part configures interfaces,
and \ttt{route..routeend.} part contains static routes.
The format of these sections roughly corresponds to the output
of the \ttt{ifconfig} and \ttt{netstat -rn} Unix commands.

An interface entry begins with a \ttt{name:} field, and lasts until
the next \ttt{name:} (or until \ttt{ifconfigend.}). It may
be broken into several lines.

Accepted interface fields are:

\begin{itemize}
  \item \ttt{name:} - arbitrary interface name (e.g. eth0, ppp0)
  \item \ttt{inet\_addr:} - IP address
  \item \ttt{Mask:} - netmask
  \item \ttt{Groups:} Multicast groups. 224.0.0.1 is added automatically,
     and 224.0.0.2 also if the node is a router (IPForward==true).
  \item \ttt{MTU:} - MTU on the link (e.g. Ethernet: 1500)
  \item \ttt{Metric:} - integer route metric
  \item flags: \ttt{BROADCAST}, \ttt{MULTICAST}, \ttt{POINTTOPOINT}
\end{itemize}

The following fields are parsed but ignored: \ttt{Bcast},\ttt{encap},
\ttt{HWaddr}.

Interface modules set a good default for MTU, Metric (as $2*10^9$/bitrate) and
flags, but leave \fvar{inet\_addr} and \fvar{Mask} empty. \fvar{inet\_addr} and
\fvar{mask} should be set either from the routing file or by a dynamic network
configuration module.

The route fields are:

\begin{verbatim}
Destination  Gateway  Netmask  Flags  Metric Interface
\end{verbatim}

\fvar{Destination}, \fvar{Gateway} and \fvar{Netmask} have the usual meaning.
The \fvar{Destination} field should either be an IP address or ``default''
(to designate the default route). For \fvar{Gateway}, \ttt{*} is also
accepted with the meaning \ttt{0.0.0.0}.

\fvar{Flags} denotes route type:

\begin{itemize}
  \item \textit{H} ``host'': direct route (directly attached to the router), and
  \item \textit{G} ``gateway'': remote route (reached through another router)
\end{itemize}

\fvar{Interface} is the interface name, e.g. \ttt{eth0}.

\begin{important}
The meaning of the routes where the destination is a multicast address
has been changed in version 1.99.4. Earlier these entries was used
both to select the outgoing interfaces of multicast datagrams
sent by the higher layer (if multicast interface was otherwise unspecified)
and to select the outgoing interfaces of datagrams that are received from
the network and forwarded by the node.

From version 1.99.4 multicast routing applies reverse path forwarding.
This requires a separate routing table, that can not be populated from
the old routing table entries. Therefore simulations that use multicast
forwarding can not use the old configuration files, they should be
migrated to use an \nedtype{IPv4NetworkConfigurator} instead.

Some change is needed in models that use link-local multicast too.
Earlier if the IP module received a datagram from the higher layer
and multiple routes was given for the multicast group,
then IP sent a copy of the datagram on each interface of that routes.
From version 1.99.4, only the first matching interface is used (considering
longest match). If the application wants to send the multicast datagram
on each interface, then it must explicitly loop and specify the multicast
interface.
\end{important}

% FIXME 'H' and 'G' flags should be independent. Now they excludes each other, the parser sets route.type to the last one.
%       H = host/network
%       G = indirect/direct

% TODO warn that multicast configuration has changed


\section{Applications}

The applications described in this section uses the services of the network
layer only, they do not need transport layer protocols.
They can be used with both IPv4 and IPv6.

\subsection{IP traffic generators}

Traffic generators that connect directly to IP (without using TCP or UDP):
\nedtype{IIPvXTraffixGenerator} (prototype).
 \nedtype{IPvXTrafGen},

Sends IP or IPv6 datagrams to the given address at the given \fpar{sendInterval}.
The \fpar{sendInterval} parameter can be a constant or a random value (e.g. exponential(1)).
If the \fpar{destAddresses} parameter contains more than one address, one
of them is randomly for each packet. An address may be given in the
dotted decimal notation (or, for IPv6, in the usual notation with colons),
or with the module name. (The \cppclass{L3AddressResolver} class is used to resolve
the address.) To disable the model, set destAddresses to "".

The \nedtype{IPvXTrafGen} sends messages with length \fpar{packetLength}.
The sent packet is emitted in the \fsignal{sentPk} signal.
The length of the sent packets can be recorded as scalars and vectors.

The \nedtype{IPvXTrafSink} can be used as a receiver of the packets
generated by the traffic generator. This module emits the packet
in the \fsignal{rcvdPacket} signal and drops it. The \ttt{rcvdPkBytes}
and \ttt{endToEndDelay} statistics are generated from this signal.

The \nedtype{IPvXTrafGen} can also be the peer of the traffic generators;
it handles the received packets exactly like \nedtype{IPvXTrafSink}.

You can see an example usage of these applications in \ffilename{examples/inet/routerperf/omnetpp.ini}
simulaton.

\subsection{The PingApp application}

The \nedtype{PingApp} application
generates ping requests and calculates the packet loss and round trip
parameters of the replies.

Start/stop time, sendInterval etc. can be specified via parameters. An address
may be given in the dotted decimal notation (or, for IPv6, in the usual
notation with colons), or with the module name.
(The \cppclass{L3AddressResolver} class is used to resolve the address.)
To disable send, specify empty destAddr.

Every ping request is sent out with a sequence number, and replies are
expected to arrive in the same order. Whenever there's a jump in the
in the received ping responses' sequence number (e.g. 1, 2, 3, 5), then
the missing pings (number 4 in this example) is counted as lost.
Then if it still arrives later (that is, a reply with a sequence number
smaller than the largest one received so far) it will be counted as
out-of-sequence arrival, and at the same time the number of losses is
decremented. (It is assumed that the packet arrived was counted earlier as a loss,
which is true if there are no duplicate packets.)

Uses \msgtype{PingPayload} as payload for the ICMP(v6) Echo Request/Reply packets.

\subsubsection*{Parameters}

\begin{itemize}
  \item \fpar{destAddr}: destination address
  \item \fpar{srcAddr}: source address (useful with multi-homing)
  \item \fpar{packetSize}: of ping payload, in bytes (default is 56)
  \item \fpar{sendInterval}: time to wait between pings (can be random, default is 1s)
  \item \fpar{hopLimit}: TTL or hopLimit for IP packets (default is 32)
  \item \fpar{count}: stop after \fpar{count} ping request, 0 means continuously
  \item \fpar{startTime}: send first ping request at \fpar{startTime}
  \item \fpar{stopTime}: time of finish sending, 0 means forever
  \item \fpar{printPing}: dump on stdout (default is \fkeyword{false})
\end{itemize}

\subsubsection*{Signals and Statistics}

\begin{itemize}
  \item \fsignal{rtt} value of the round trip time
  \item \fsignal{numLost} number of lost packets
  \item \fsignal{outOfOrderArrivals} number of packets arrived out-of-order
  \item \fsignal{pingTxSeq} sequence number of the sent ping request
  \item \fsignal{pingRxSeq} sequence number of the received ping response
\end{itemize}

% FIXME seqNo should be part of ICMPMessage

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "usman"
%%% End:

